package Net::SubnetScan;

use JIP::ToolSet;
use Exporter::Lite;
use Carp qw( croak );
use IPC::Open3 qw( open3 );
use Readonly qw( Readonly );
use English qw( -no_match_vars );

our $EXPORT_OK = qw( findActiveHosts );

Readonly my $NMAP_REGEX => qr/Interesting\sports\son\s
                             (\d+\.\d+\.\d+\.\d+):
                             /msx;

sub findActiveHostsInSubnet {
    my $subnetMask = shift;

    my $cmdline = join ' ', (
        'nmap',
        '-n',
        '-sT',
        '-p21',
        $subnetMask,
        '2>/dev/null',
    );

    open3( \*WRITE, \*READ, \*ERROR, $cmdline )
        or croak 'cannot spawn nmap'. $OS_ERROR;

    my @serversOnline;

    # read the command output
    while ( my $eachLine = <READ> ) {
        if ( my( $IPAddress ) = $eachLine =~ $NMAP_REGEX ) {
            push @serversOnline, $IPAddress;
        }
    }

    close( WRITE );
    close( READ );
    close( ERROR );

    return @serversOnline;
}

1;

__END__

=head1 NAME

Net::SubnetScan - класс для поиска активных хостов в подсети

=head1 SYNOPSIS

пример использования модуля:

    # findActiveHosts() требует обязательного импортирования
    use Net::SubnetScan qw( findActiveHosts );

    say foreach findActiveHosts('81.89.188.0/23');

=cut

